package com.ai4ai.laika.card;

import com.ai4ai.laika.LaikaApplication;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Service
public class CardService {

    public static final String PROJECT_PATH = "D:\\workspace\\Ideawork\\laika2";

    @Autowired
    FreeMarkerConfigurationFactory freeMarkerConfigurationFactory;

    //通过freemarker生成文件
    private String createFile(String filePath, String fileName,String tempName,Map dataMap){
        String path = null;
        try {

            Configuration configuration = freeMarkerConfigurationFactory.createConfiguration();


            //String filePath = "D:\\workspace\\Ideawork\\laika2";
            //String fileName = "abc.java";
            //String tempName = "test.ftl";
            //创建配置实例
//            Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);

            //设置编码
            configuration.setDefaultEncoding("UTF-8");

//            //ftl模板文件
//            configuration.setClassForTemplateLoading(LaikaApplication.class,"/freemarker/");
//            configuration.setClassLoaderForTemplateLoading(LaikaApplication.class.getClassLoader(),"/freemarker/");
//            configuration.setDirectoryForTemplateLoading(new File("D:\\workspace\\Ideawork\\laika\\src\\main\\resources\\freemarker"));
//            configuration.setServletContextForTemplateLoading();
            //获取模板
            Template template = configuration.getTemplate(tempName);

            path = filePath+File.separator+fileName;
            //输出文件
            File outFile = new File(path);

            //如果输出目标文件夹不存在，则创建
            if (!outFile.getParentFile().exists()){
                outFile.getParentFile().mkdirs();
            }

            //将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));

//            Map dataMap = new HashMap<>();
//            dataMap.put("title","yanglei");
            //生成文件
            template.process(dataMap, out);

            //关闭流
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }

    //生成pom.xml文件
    public String createPomFile(){
        String filePath = PROJECT_PATH;
        String fileName = "pom.xml";
        String tempName = "pom.ftl";
        Map dataMap = new HashMap();

        return createFile(filePath,fileName,tempName,dataMap);
    }

    //生成Stringboot入口 Application.java
    public String createApplicationFile(){
        String filePath = PROJECT_PATH + "\\src\\main\\java\\com\\ai4ai\\laika2";
        String fileName = "Laika2Application.java";
        String tempName = "application.ftl";
        Map dataMap = new HashMap();

        return createFile(filePath,fileName,tempName,dataMap);
    }

    //生成阿里云FC函数部署文件
    public String createFCDeployFile(){
        return null;
    }
    //生成阿里云FC函数模板文件
    public String createFCTemplateFile(){
        return null;
    }



    //一个命令行简单测试
    public String execCmdWithResult() {
        try {
            String command = "ping 127.0.0.1";
            //接收正常结果流
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            //接收异常结果流
            ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
            CommandLine commandline = CommandLine.parse(command);
            DefaultExecutor exec = new DefaultExecutor();
            exec.setExitValues(null);
            //设置一分钟超时
            ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
            exec.setWatchdog(watchdog);
            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
            exec.setStreamHandler(streamHandler);
            exec.execute(commandline);
            //不同操作系统注意编码，否则结果乱码
            String out = outputStream.toString("GBK");
            String error = errorStream.toString("GBK");
            System.out.println(out + error);
            return out + error;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

//    public void execComWin(){
//        try {
//            String command = "ping 127.0.0.1";
//            Process process = Runtime.getRuntime().exec(command);//通过cmd程序执行cmd命令
//            //process.waitFor();
//
//            //读取屏幕输出
//            BufferedReader strCon = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
//            String line;
//            while ((line = strCon.readLine()) != null) {
//                System.out.println(line);
//            }
//        } catch (Exception e){
//            e.printStackTrace();
//        }
//    }

    //win运行bat文件
    public void execBatFile(){
        try {
            String command = PROJECT_PATH+"\\package.bat";
            Process process = Runtime.getRuntime().exec(command);//通过cmd程序执行cmd命令
            //process.waitFor();

            //读取屏幕输出
            BufferedReader strCon = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
            String line;
            while ((line = strCon.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    //linux运行shell文件
    public void execShellFile(){
        try {

            String command="/mnt/d/workspace/Ideawork/laika2/package.sh";
            //String command = PROJECT_PATH+"\\test.bat";
            Process process = Runtime.getRuntime().exec(command);//通过cmd程序执行cmd命令
            //process.waitFor();

            //读取屏幕输出
            BufferedReader strCon = new BufferedReader(new InputStreamReader(process.getInputStream(),"UTF8"));
            String line;
            while ((line = strCon.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
